import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { ListView } from 'antd-mobile';
import { Link } from 'react-router-dom';

import '../css/skin.css';
import '../css/apply-list.css';

function MyBody(props) {
  return (
    <div className="am-list-body my-body">
      <span style={{ display: 'none' }}>you can custom body wrap element</span>
      {props.children}
    </div>
  );
}

let datas = [];
let pageIndex = 0;

const dataBlobs = {};
let sectionIDs = [];
let rowIDs = [];

// 贷款状态
const LOAN_STATE = ['未知','拒贷','批贷已放款','批贷未放款','借款人放弃申请','审核中','待放款'];

function genData(pIndex = 0) {
  rowIDs = [];
  let len = 4;
  if( datas.length<4 ){ len=datas.length }
  for (let jj = 0; jj < len; jj++) {
    const rowName = `R${jj}`;
    rowIDs.push(rowName);
    dataBlobs[rowName] = rowName;
  }
  rowIDs = [...rowIDs];
}

// 格式化时间戳 => yyyy-m-d
function fmtDate(obj){
  var date =  new Date(obj);
  var y = 1900+date.getYear();
  var m = "0"+(date.getMonth()+1);
  var d = "0"+date.getDate();
  return y+"-"+m.substring(m.length-2,m.length)+"-"+d.substring(d.length-2,d.length);
}

class companyList extends React.Component {
  constructor(props) {
    super(props);
    const getSectionData = (dataBlob, sectionID) => dataBlob[sectionID];
    const getRowData = (dataBlob, sectionID, rowID) => dataBlob[rowID];

    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
      sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
    });

    this.state = {
      dataSource,
      isLoading: true,
      height: document.documentElement.clientHeight * 3 / 4,
    };
  }

  componentDidMount() {

    const hei = document.documentElement.clientHeight - ReactDOM.findDOMNode(this.lv).parentNode.offsetTop;

    // ajax 取数据
    let _searchParam = {
      "current": 0,
      "size": 4,
    };
    fetch('http://58.220.10.23:8001/api/loanapply/totakelist', {
  	  method: 'POST',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(_searchParam),
	   }).then(response => response.json())
	   .then(data=>{
        if( data.status===0 ){
          datas = [];
          for( let i=0; i<data.data.length; i++){
            let item = {};
            item.id = data.data[i].idString;
            item.time = fmtDate(data.data[i].applyTime);
            item.name = data.data[i].identityName;
            item.money = data.data[i].amount;
            item.priest = data.data[i].loanPeriod;
            item.state = LOAN_STATE[data.data[i].orderState];
            datas.push(item);
          }
        }else{
          //Toast.fail(data.msg, 1);
        }
	   }).catch(e=>{
       console.log(e);
     });

    // simulate initial Ajax
    setTimeout(() => {
      genData();
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(dataBlobs, rowIDs),
        isLoading: false,
        height: hei,
      });
    }, 600);
  }

  onEndReached = (event) => {
    // load new data
    // hasMore: from backend data, indicates whether it is the last page, here is false
    if (this.state.isLoading && !this.state.hasMore) {
      return;
    }
    console.log('reach end', event);
    this.setState({ isLoading: true });
    setTimeout(() => {
      genData(++pageIndex);
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(dataBlobs, rowIDs),
        isLoading: false,
      });
    }, 1000);
  }

  render() {
    const separator = (sectionID, rowID) => (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: '#F5F5F9',
          height: 8,
          borderTop: '1px solid #ECECED',
          borderBottom: '1px solid #ECECED',
        }}
      />
    );
    let index = datas.length - 1;
    const row = (rowData, sectionID, rowID) => {
      if (index < 0) {
        index = datas.length - 1;
      }
      const obj = datas[index--];
      console.log(obj);
      return(
        <ul className="bor-list-wrap">
          <li className="bor-list">
  	 				<p className="bor-time">{obj.time}</p>
  	 				<div className="info-wrap">
  	 					<div className="info-box">
  	 						<p className="borinfo-title">姓名</p>
  	 						<p className="borinfo-detail">{obj.name}</p>
  	 					</div>
  	 					<div  className="info-box">
  	 						<p className="borinfo-title">借款金额</p>
  	 						<p className="borinfo-detail"><i className="data-money text-color">{obj.money}</i>元</p>
  	 					</div>
  	 					<div  className="info-box">
  	 						<p className="borinfo-title">借款周期</p>
  	 						<p className="borinfo-detail">{obj.priest}月</p>
  	 					</div>
  	 				</div>
  	 				<hr className="line" />
      			<p className="bor-state">备注信息：<i className="text-color">{obj.state}</i></p>
            <Link to={{
              pathname: "/companyDetail",
              query: {id: obj.id}
            }} className="btn-brodetail bg-color">查看详情</Link>

      		</li>
        </ul>
      );
    };

    return (
      <div className="skin-orange">
        <ListView
          ref={el => this.lv = el}
          dataSource={this.state.dataSource}
          renderHeader={() => <div><p className="b-title bg-color">
            <span className="bg-color title-text white">精确筛选</span>
          </p>
            <div className="limit-order">
              <span className="limit-wrap">可接单数<i className="limit-num text-color">5</i>/5</span>
            </div>
            </div>
          }
          renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
            {this.state.isLoading ? '加载中...' : '加载完成'}
          </div>)}
          renderBodyComponent={() => <MyBody />}
          renderRow={row}
          renderSeparator={separator}
          style={{
            height: this.state.height,
            overflow: 'auto',
          }}
          pageSize={4}
          onScroll={() => { console.log('scroll'); }}
          scrollRenderAheadDistance={500}
          onEndReached={this.onEndReached}
          onEndReachedThreshold={10}
        />
      </div>
    );
  }
}

export default companyList;
